package mayton.image;


/**
 * Utils
 *
 * @author      Mark Kovalyov lordmayton@mail.ru
 * @license     http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3
 */
public class Utils {

    /**
     * Наименьшая степень 2 не уступающая значению x
     * @param x
     * @return
     */
    public static int clp2(int x){
        x = x - 1;
        x = x | (x >> 1);
        x = x | (x >> 2);
        x = x | (x >> 4);
        x = x | (x >> 8);
        x = x | (x >> 16);
        return x + 1;
    }

    /**
     * Подсчёт количества битов
     * @param x
     * @return
     */
    public static int pop(int x){
        int n;
        n = (x >> 1) & 0x77777777;
        x = x - n;
        n = (x >> 1) & 0x77777777;
        x = x - n;
        n = (x >> 1) & 0x77777777;
        x = x - n;
        n = (x >> 1) & 0x77777777;
        x = x - n;
        x = (x + (x >> 4)) & 0x0F0F0F0F;
        x = x * 0x01010101;
        return x >> 24;
    }

    public static int nlz(int x){
        int pop = x;
        x = x | (x >>  1);
        x = x | (x >>  2);
        x = x | (x >>  4);
        x = x | (x >>  8);
        x = x | (x >> 16);
        return pop(~x);
    }

    public static int nlz_(int x){
        int n;
        if (x == 0) return 32;
        n = 1;
        if ((x >> 16) == 0) {n += 16; x <<= 16; }
        if ((x >> 24) == 0) {n +=  8; x <<=  8; }
        if ((x >> 28) == 0) {n +=  4; x <<=  4; }
        if ((x >> 30) == 0) {n +=  2; x <<=  2; }
        n -= ( x >> 31);
        return n;
    }

    /**
     * Целочисленный логарифм по основанию 2
     * @param x
     * @return
     */
    public static int ilog2(int x){
        return pop(x)-1;
    }


}
